#include <sys/types.h>          
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <iostream>
#include <cstring>
#include <string>

void Usage()
{
    std::cout<<"Usage:\n"<<"./UdpServer ip port"<< std::endl;
}
enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR,
    USAGE_ERROR
}; 

int main(int argc,char* argv[])
{
    if(argc != 3)
    {   
        Usage();
        exit(USAGE_ERROR);
    }
    //接收服务器的ip和port
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    //1.创建 Udp Stocket套接字
    int sockfd = socket(AF_INET,SOCK_DGRAM,0);
    if(sockfd < 0)
    {
        std::cout<<"socket error,"<<strerror(errno) <<", "<<errno <<std::endl;
        exit(SOCKET_ERROR);
    }

    // 构建目标主机的socket信息
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());

    // udp client首次发送数据的时候，OS会自己自动随机的给client进行bind 防止client port冲突。要bind，必然要和port关联！
    // 首次发送数据的时候bind

    // 直接通信即可
    std::string message;
    while(true)
    {
        std::cout << "Please Enter# ";
        std::getline(std::cin, message);
        sendto(sockfd, message.c_str(), message.size(), 0, (struct sockaddr*)&server, sizeof(server));

        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        char buffer[1024];
        ssize_t n = recvfrom(sockfd, buffer, sizeof(buffer)-1, 0, (struct sockaddr*)&peer, &len);
        if(n > 0)
        {
            buffer[n] = 0;
            std::cout << "server echo# " << buffer << std::endl;
        }
    }
    return 0;
}